<template>
  <el-dialog v-model="open" :title="title" width="800px" append-to-body :close-on-click-modal="false">
    <el-form ref="dialogRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="原折扣">
        <span>{{ form.discountPercent }}%</span>
      </el-form-item>

      <el-form-item label="修改折扣" prop="discount">
        <el-input v-model="form.discount" type="number" placeholder="折扣">
          <template #append>%</template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script setup>
import { getCurrentInstance } from '@vue/runtime-core'
import { reactive, watch } from 'vue'
import { toRefs } from '@vueuse/shared'
import { editDiscount } from '../../../../../api/ven/member'
import { dayjs } from 'element-plus'

const { proxy } = getCurrentInstance()

const props = defineProps({
  props: {
    type: Object,
    default: () => ({
      open: false,
      title: ''
    })
  },
  cardList: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['submitForm'])

const formBase = {
  expireDateType: '1'
}
const data = reactive({
  form: {
    ...formBase
  },
  rules: {
    discount: [{
      validator: (rule, value, callback) => {
        if (!value) {
          callback('必填')
          return
        } else {
          if (value < 0 || value > 100) {
            callback('输入有误')
            return
          }
        }
        callback()
      }, required: true }]
  }
})
const { open, title } = toRefs(props.props)
const { form, rules } = toRefs(data)

watch(open, (val) => {
  if (val) {
    const { id, discountPercent } = props.props.data
    form.value = _.assign({
      memberId: id,
      discountPercent
    }, { ...formBase })
  } else {
    proxy.resetForm('dialogRef')
  }
})


function submitForm() {
  proxy.$refs['dialogRef'].validate((valid) => {
    if (valid) {
      editDiscount(form.value).then(() => {
        proxy.$modal.msgSuccess('操作成功')
        open.value = false
        emit('submitForm')
      })
    }
  })
}

function cancel() {
  open.value = false
}

</script>

<style scoped>

</style>
